"""
日志管理模块
"""

import logging
import sys
from pathlib import Path
from datetime import datetime
from logging.handlers import RotatingFileHandler
from typing import Optional


class Logger:
    """日志管理器"""
    
    def __init__(self, name: str = "FileConverter", config=None):
        self.logger = logging.getLogger(name)
        self.config = config
        
        # 避免重复添加处理器
        if self.logger.handlers:
            return
        
        # 设置日志级别
        log_level = getattr(logging, (config.log.log_level if config else "INFO").upper())
        self.logger.setLevel(log_level)
        
        # 创建日志目录
        log_dir = Path("logs")
        log_dir.mkdir(exist_ok=True)
        
        # 创建格式化器
        formatter = logging.Formatter(
            '%(asctime)s - %(name)s - %(levelname)s - %(funcName)s:%(lineno)d - %(message)s',
            datefmt='%Y-%m-%d %H:%M:%S'
        )
        
        # 文件处理器
        if not config or config.log.log_to_file:
            max_bytes = (config.log.log_file_size_mb if config else 10) * 1024 * 1024
            backup_count = config.log.max_log_files if config else 10
            
            file_handler = RotatingFileHandler(
                log_dir / f"app_{datetime.now().strftime('%Y%m%d')}.log",
                maxBytes=max_bytes,
                backupCount=backup_count,
                encoding='utf-8'
            )
            file_handler.setLevel(logging.DEBUG)
            file_handler.setFormatter(formatter)
            self.logger.addHandler(file_handler)
        
        # 控制台处理器
        if not config or config.log.log_to_console:
            console_handler = logging.StreamHandler(sys.stdout)
            console_handler.setLevel(logging.INFO)
            console_handler.setFormatter(formatter)
            self.logger.addHandler(console_handler)
    
    def debug(self, message: str, *args, **kwargs):
        """调试日志"""
        self.logger.debug(message, *args, **kwargs)
    
    def info(self, message: str, *args, **kwargs):
        """信息日志"""
        self.logger.info(message, *args, **kwargs)
    
    def warning(self, message: str, *args, **kwargs):
        """警告日志"""
        self.logger.warning(message, *args, **kwargs)
    
    def error(self, message: str, exc_info=None, *args, **kwargs):
        """错误日志"""
        self.logger.error(message, exc_info=exc_info, *args, **kwargs)
    
    def critical(self, message: str, exc_info=None, *args, **kwargs):
        """严重错误日志"""
        self.logger.critical(message, exc_info=exc_info, *args, **kwargs)
    
    def exception(self, message: str, *args, **kwargs):
        """异常日志（自动包含异常信息）"""
        self.logger.exception(message, *args, **kwargs)
